<?php

/**
 * @Author: kendy
 * @Date:   2020-01-15 15:42:05
 * @Last Modified by:   jiayanting
 * @Last Modified time: 2020-03-31 09:18:33
 */
namespace app\api\controller;
use think\Db;
use think\Request;
use think\Controller;
use think\Loader;
use app\api\model\Payments as p;
class Wxpays extends Nocommon
{
    public function getWxpays()
    { 
        //微信支付
        Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');
        $config = new \WxPayConfig();
        $WxPay  = new \WxPayApi();
        $WxData = new \WxPayUnifiedOrder();
        $order_sn = input("order_sn"); 
        $order_type = input("order_type");//订单类型 订单类型 1酒店，2景点，3跟团
        $orderTable = $this->getFieldByType($order_type); 
        $cnt = Db::name($orderTable[0])
        ->where(['order_sn'=>$order_sn])
        ->find();  

         if(empty($cnt)) 
           $this->apiReturn('400','订单信息为空',0); 
        $order_price = $cnt["order_price"];
        $uid = $cnt[$orderTable[1]];
        $passback_params = base64_encode($uid."@".$order_type);
        $dataArr = array(
            'out_trade_no'     => $order_sn,            //订单号
            'body'             => '支付购买商品费用'.$order_price.'元',                         //商品名
            'total_fee'        => $order_price * 100,        //支付总金额
            'trade_type'       => 'APP',                     //支付途径
            'nonce_str'        => $WxPay->getNonceStr(),    //32位随进数
            'notify_url'       => 'http://api.lancly.com/api/Wxpays/aliNotify',// 异步通通知地址
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'attach'           => $passback_params
        ); 
        $WxData->SetOut_trade_no($dataArr['out_trade_no']);
        $WxData->SetBody($dataArr['body']);
        $WxData->SetTotal_fee($dataArr['total_fee']);
        $WxData->SetTrade_type($dataArr['trade_type']);
        $WxData->SetNonce_str($dataArr['nonce_str']);
        $WxData->SetAttach($dataArr['attach']);
        $WxData->SetNotify_url($dataArr['notify_url']);
        $WxData->SetSpbill_create_ip($dataArr['spbill_create_ip']);
        $WxData->SetSign($config);
        $return = $WxPay->unifiedOrder($config,$WxData);

        if (array_key_exists('result_code',$return) && array_key_exists('return_code',$return) && $return['result_code'] == 'SUCCESS' && $return['return_code'] == 'SUCCESS'){
            $signArr = array(
                'appid'     =>$config->GetAppId(),
                'partnerid' =>$config->GetMerchantId(),
                'timestamp' =>time(),
                'package'   =>'Sign=WXPay',
                'noncestr'  =>$return['nonce_str'],
                'prepayid'  =>$return['prepay_id']
            );
            $setSignClass = new \WxPayResults();
            $setSignClass->SetData('sign',$return['sign']);
            $setSignClass->SetData('appid',$signArr['appid']);
            $setSignClass->SetData('partnerid',$signArr['partnerid']);
            $setSignClass->SetData('timestamp',$signArr['timestamp']);
            $setSignClass->SetData('package',$signArr['package']);
            $setSignClass->SetData('noncestr',$signArr['noncestr']);
            $setSignClass->SetData('prepayid',$signArr['prepayid']);
            $signToApp = $setSignClass->MakeSign($config); 
        /*    echo "<pre>";
            print_r(array('code'=>'200','msg'=>'请求成功','data'=>array('prepay_id'=>$return['prepay_id'],'sign'=>$signToApp,'timestamp'=>$signArr['timestamp'],'noncestr'=>$signArr['noncestr'])));*/
            $response = array('prepay_id'=>$return['prepay_id'],'sign'=>$signToApp,'timestamp'=>$signArr['timestamp'],'noncestr'=>$signArr['noncestr'],'order_id'=>$cnt['order_id']);
              return $this->apiReturn('200','请求成功',$response); 
        }else{ 
              return $this->apiReturn('401','提交失败',0); 
        }

    }
 
     public function aliNotify(){	    
        $testxml  = file_get_contents("php://input");  
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA)); 
        $result = json_decode($jsonxml, true);//转成数组，
        if($result){
       //如果成功返回了 
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
         //执行业务逻辑 
         //商户订单号
        //file_put_contents("obj1.txt", json_encode($result));
        $obj = array();
        $obj["trade_no"] = $result['transaction_id'];
        $obj["out_trade_no"] = $result['out_trade_no'];
        $obj["total_amount"] = (float)$result['total_fee']/100;
        $extras = explode("@",base64_decode($result['attach']));
        $obj["uid"] = $extras[0];
        $obj["order_type"] = $extras[1];
        $obj["pay_type"] = 2;
        file_put_contents("obj2.txt", json_encode($obj));
        //支付成功业务逻辑
            
           $p = new p();
            if(in_array($obj['order_type'], [1,2,3])){ 
              $rs = $p->complatePay($obj);
            }
             if($obj['order_type'] == 4){ 
              $rs = $p->complateJlouPay($obj);
            }  
            if($obj['order_type'] == 5){ 
              $rs = $p->complateBargainPay($obj);
            }
            if($obj['order_type'] == 6){
                $rs = $p->complateVotePay($obj);
            }
            if($rs['status'] == 200){
              echo 'SUCCESS';
            }else{
              echo 'FAIL';
            }
        }else{
            echo 'FAIL';
        } 
     }
}

     /**
	 * [getFieldByType 根据类型获取字段]
	 * @Author   kendy
	 * @DateTime 2020-02-11T13:01:53+0800
	 * @param    [type]                   $payType [支付类型 1酒店，2景点，3跟团]
	 * @return   [type]                            []
	 */
	public function getFieldByType($orderType){  
	      if($orderType==1){
	      	 return  ['hotel_order','uid','hotel','hotel_id','hotel_id','hotel_name']; 
	      }
	      if($orderType==2){
	         return  ['tour_order','user_id','tours','tour_id','tour_id','tour_name']; 
	      }
	      if($orderType==3){ 
	        return   ['gtour_order','user_id','group_tour','id','gtour_id','gtour_title']; 
	      } 
	}

    /*
   * 退款回调
   */
    public function refundNotify()
    {
        $testxml  = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $results = json_decode($jsonxml, true);//转成数组，
        if($results['return_code']=='SUCCESS') {
            $key = strtolower(MD5('71ed921f74da0b04a253a26d17437d56'));
            $decrypt = base64_decode($results['req_info'], true);
            $xml = openssl_decrypt($decrypt, 'aes-256-ecb', $key, OPENSSL_RAW_DATA);
            $jsonxml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
            $result = json_decode($jsonxml, true);
            //return_code此字段是通信标识，非交易标识，交易是否成功需要查看refund_status来判断
            if ($result) {
                if ($result['refund_status'] == 'SUCCESS') {
                    echo '退款成功';
                    Db::name('jlou_order')->where('order_sn', $result['out_trade_no'])->setField('is_refund', 1);
                    $data = [
                        'refund_sn' => $result['out_refund_no'],
                        'order_sn' => $result['out_trade_no'],
                        'refund_money' => $result['settlement_refund_fee']/100,
                        'refund_time' => $result['success_time'],
                        'pay_type' => 2
                    ];
                    Db::name('jlou_refund')->insert($data);
                } else if ($result['refund_status'] == 'CHANGE') {
                    echo '退款异常';
                } else if ($result['refund_status'] == 'REFUNDCLOSE') {
                    echo '退款关闭';
                }
            }
        }
        return '<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';

    }
    /**
     * [AffirmWexinNotify 待确认退款]
     * @Author   kendy
     * @DateTime 2020-03-27T09:55:01+0800
     */
    public function WexinNotify(){
        file_put_contents("123.txt",json_encode($_POST));
        $testxml  = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $results = json_decode($jsonxml, true);//转成数组，
        if($results['return_code']=='SUCCESS') {
            $key = strtolower(MD5('71ed921f74da0b04a253a26d17437d56'));
            $decrypt = base64_decode($results['req_info'], true);
            $xml = openssl_decrypt($decrypt, 'aes-256-ecb', $key, OPENSSL_RAW_DATA);
            $jsonxml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
            $result = json_decode($jsonxml, true);
            //return_code此字段是通信标识，非交易标识，交易是否成功需要查看refund_status来判断
            if ($result) {
                if ($result['refund_status'] == 'SUCCESS') {  
                   //退款成功业务逻辑
                     $hotelOrder = Db::name('hotel_order')
                     ->where('order_sn',$result['out_trade_no'])
                     ->find();
                     if(!empty($hotelOrder)){
                        $obj['order_sn'] = $hotelOrder['order_sn'];
                        $obj['refund_trade_no'] = $result['out_refund_no'];
                        $obj['object_id'] = $hotelOrder['hotel_id']; 
                        $obj['object_type'] = 4; 
                        $obj['user_id'] = $hotelOrder['uid'];
                        $obj['refund_status'] = 1;
                        $obj['refund_reason'] = "自动退款";
                        $obj['order_price'] = $result['settlement_refund_fee']/100; 
                        $orderRefund = new ore(); 
                        $orderRefund->addOrderRefund($obj);  
                        //新增订单日志
                        $logOrder = [];
                        $logOrder['order_id'] = $hotelOrder['order_id'];
                        $logOrder['order_status'] = 4;
                        $logOrder['log_content'] = "订单已退款";
                        $logOrder['user_id'] = $hotelOrder['uid'];
                        $logOrder['create_time'] = time();
                        $logOrder['order_type'] = 4;
                        Db::name('log_orders')->insert($logOrder);
                       //创建一条支付流水记录
                        $lm = [];
                        $lm['target_type'] = 0;
                        $lm['target_id'] = $hotelOrder['uid'];
                        $lm['data_id'] = 1;
                        $lm['data_src'] = 1;
                        $lm['remark'] = '订单【'.$hotelOrder['order_sn'].'】退款￥'.$hotelOrder['order_price'];
                        $lm['money_type'] = 0;
                        $lm['money'] =$hotelOrder['order_price'];
                        $lm['pay_type'] = $hotelOrder['pay_type'];
                        $lm['create_time'] = date('Y-m-d H:i:s');
                        Db::name('log_moneys')->insert($lm);

                     } 
                } else if ($result['refund_status'] == 'CHANGE') {
                    echo '退款异常';
                } else if ($result['refund_status'] == 'REFUNDCLOSE') {
                    echo '退款关闭';
                }
            }
        }
        return '<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'; 
    }

}